// 高级搜索组件

import React, { useState, useCallback, useEffect } from 'react';
import { Search, Filter, X, ChevronDown, ChevronUp } from 'lucide-react';
import { FileItem } from '../types/filesystem';
import { FileSystemService } from '../services/filesystem';

interface SearchFilters {
  fileExtensions: string[];
  includeContent: boolean;
  caseSensitive: boolean;
  useRegex: boolean;
  maxResults: number;
}

interface AdvancedSearchProps {
  workspacePath?: string;
  onSearchResults: (results: FileItem[]) => void;
  onClose: () => void;
  className?: string;
}

/**
 * 高级搜索组件
 */
export const AdvancedSearch: React.FC<AdvancedSearchProps> = ({
  workspacePath,
  onSearchResults,
  onClose,
  className = '',
}) => {
  const [query, setQuery] = useState('');
  const [filters, setFilters] = useState<SearchFilters>({
    fileExtensions: [],
    includeContent: false,
    caseSensitive: false,
    useRegex: false,
    maxResults: 100,
  });
  const [isExpanded, setIsExpanded] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const [showHistory, setShowHistory] = useState(false);

  // 常用文件扩展名
  const commonExtensions = [
    'ts', 'tsx', 'js', 'jsx', 'py', 'rs', 'java', 'cpp', 'c', 'go',
    'html', 'css', 'json', 'md', 'xml', 'yaml', 'toml', 'sh', 'sql'
  ];

  // 加载搜索历史
  useEffect(() => {
    const savedHistory = localStorage.getItem('file-search-history');
    if (savedHistory) {
      try {
        setSearchHistory(JSON.parse(savedHistory));
      } catch (error) {
        console.error('Failed to load search history:', error);
      }
    }
  }, []);

  // 保存搜索历史
  const saveSearchHistory = useCallback((searchQuery: string) => {
    if (!searchQuery.trim()) return;

    setSearchHistory(prev => {
      const newHistory = [searchQuery, ...prev.filter(item => item !== searchQuery)].slice(0, 10);
      localStorage.setItem('file-search-history', JSON.stringify(newHistory));
      return newHistory;
    });
  }, []);

  // 执行搜索
  const performSearch = useCallback(async () => {
    if (!query.trim() || !workspacePath) return;

    setIsSearching(true);
    
    try {
      const results = await FileSystemService.searchFiles(workspacePath, query, {
        includeContent: filters.includeContent,
        fileExtensions: filters.fileExtensions.length > 0 ? filters.fileExtensions : undefined,
        maxResults: filters.maxResults,
      });

      // 应用额外的过滤器
      let filteredResults = results;

      if (filters.caseSensitive) {
        filteredResults = filteredResults.filter(file =>
          file.name.includes(query) || 
          (filters.includeContent && file.path.includes(query))
        );
      }

      if (filters.useRegex) {
        try {
          const regex = new RegExp(query, filters.caseSensitive ? 'g' : 'gi');
          filteredResults = filteredResults.filter(file =>
            regex.test(file.name) || 
            (filters.includeContent && regex.test(file.path))
          );
        } catch (error) {
          console.error('Invalid regex pattern:', error);
        }
      }

      onSearchResults(filteredResults);
      saveSearchHistory(query);
    } catch (error) {
      console.error('Search failed:', error);
      onSearchResults([]);
    } finally {
      setIsSearching(false);
    }
  }, [query, workspacePath, filters, onSearchResults, saveSearchHistory]);

  // 处理搜索输入
  const handleSearchInput = useCallback((value: string) => {
    setQuery(value);
    
    // 实时搜索（防抖）
    const timeoutId = setTimeout(() => {
      if (value.trim()) {
        performSearch();
      } else {
        onSearchResults([]);
      }
    }, 300);

    return () => clearTimeout(timeoutId);
  }, [performSearch, onSearchResults]);

  // 切换文件扩展名过滤器
  const toggleExtension = useCallback((ext: string) => {
    setFilters(prev => ({
      ...prev,
      fileExtensions: prev.fileExtensions.includes(ext)
        ? prev.fileExtensions.filter(e => e !== ext)
        : [...prev.fileExtensions, ext],
    }));
  }, []);

  // 清除所有过滤器
  const clearFilters = useCallback(() => {
    setFilters({
      fileExtensions: [],
      includeContent: false,
      caseSensitive: false,
      useRegex: false,
      maxResults: 100,
    });
  }, []);

  // 从历史记录选择
  const selectFromHistory = useCallback((historyItem: string) => {
    setQuery(historyItem);
    setShowHistory(false);
    performSearch();
  }, [performSearch]);

  return (
    <div className={`bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg ${className}`}>
      {/* 搜索头部 */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
            高级搜索
          </h3>
          <button
            onClick={onClose}
            className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
          >
            <X size={20} />
          </button>
        </div>

        {/* 搜索输入框 */}
        <div className="relative">
          <Search 
            size={16} 
            className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" 
          />
          <input
            type="text"
            placeholder="搜索文件名或内容..."
            value={query}
            onChange={(e) => handleSearchInput(e.target.value)}
            onFocus={() => setShowHistory(searchHistory.length > 0)}
            className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
          />
          
          {/* 搜索历史下拉 */}
          {showHistory && searchHistory.length > 0 && (
            <div className="absolute top-full left-0 right-0 mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg z-10 max-h-40 overflow-y-auto">
              {searchHistory.map((item, index) => (
                <button
                  key={index}
                  onClick={() => selectFromHistory(item)}
                  className="w-full px-3 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300"
                >
                  {item}
                </button>
              ))}
            </div>
          )}
        </div>

        {/* 展开/折叠过滤器 */}
        <button
          onClick={() => setIsExpanded(!isExpanded)}
          className="flex items-center mt-3 text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
        >
          <Filter size={14} className="mr-1" />
          高级过滤器
          {isExpanded ? <ChevronUp size={14} className="ml-1" /> : <ChevronDown size={14} className="ml-1" />}
        </button>
      </div>

      {/* 高级过滤器 */}
      {isExpanded && (
        <div className="p-4 space-y-4">
          {/* 搜索选项 */}
          <div className="space-y-2">
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={filters.includeContent}
                onChange={(e) => setFilters(prev => ({ ...prev, includeContent: e.target.checked }))}
                className="mr-2"
              />
              <span className="text-sm text-gray-700 dark:text-gray-300">搜索文件内容</span>
            </label>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={filters.caseSensitive}
                onChange={(e) => setFilters(prev => ({ ...prev, caseSensitive: e.target.checked }))}
                className="mr-2"
              />
              <span className="text-sm text-gray-700 dark:text-gray-300">区分大小写</span>
            </label>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={filters.useRegex}
                onChange={(e) => setFilters(prev => ({ ...prev, useRegex: e.target.checked }))}
                className="mr-2"
              />
              <span className="text-sm text-gray-700 dark:text-gray-300">使用正则表达式</span>
            </label>
          </div>

          {/* 文件类型过滤 */}
          <div>
            <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              文件类型
            </h4>
            <div className="flex flex-wrap gap-2">
              {commonExtensions.map(ext => (
                <button
                  key={ext}
                  onClick={() => toggleExtension(ext)}
                  className={`px-2 py-1 text-xs rounded ${
                    filters.fileExtensions.includes(ext)
                      ? 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
                      : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                  }`}
                >
                  .{ext}
                </button>
              ))}
            </div>
          </div>

          {/* 结果数量限制 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              最大结果数量: {filters.maxResults}
            </label>
            <input
              type="range"
              min="10"
              max="500"
              step="10"
              value={filters.maxResults}
              onChange={(e) => setFilters(prev => ({ ...prev, maxResults: parseInt(e.target.value) }))}
              className="w-full"
            />
          </div>

          {/* 操作按钮 */}
          <div className="flex items-center justify-between pt-2">
            <button
              onClick={clearFilters}
              className="text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
            >
              清除过滤器
            </button>
            <button
              onClick={performSearch}
              disabled={!query.trim() || isSearching}
              className="px-4 py-2 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isSearching ? '搜索中...' : '搜索'}
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
